<template>
	<uni-popup ref="popupRef" type="center" :is-mask-click="false" border-radius="10px 10px 10px 10px"
		style="z-index: 999;">
		<view class="show-panel">
			<view class="close-icon">
				<uni-icons type="closeempty" size="26" color="#000" @click="handleClose()"></uni-icons>
			</view>
			<view class="content">
				<view class="content-top">
					<text class="content-top-text">{{ title }}</text>
					<image class="content-top-img" src="./static/app/bg_top.png"></image>
				</view>
				<view class="content-header"></view>
				<view class="content-body">
					<view class="title">
						<text>{{ subTitle }}</text>
						<text class="content-body-version">V{{ version }}</text>
					</view>
					<view class="body">
						<scroll-view class="box-des-scroll" scroll-y="true">
							<text class="box-des">
								{{ contents }}
							</text>
						</scroll-view>
					</view>
				</view>
				<view class="footer">
					<template v-if="isApplicationStore">
						<button class="content-button" style="border: none; color: #fff" plain
							@click="jumpToApplicationStore">
							{{ downLoadBtnTextiOS }}
						</button>
					</template>
					<template v-else>
						<template v-if="!downloadSuccess">
							<view class="progress-box flex-column" v-if="downloading">
								<progress class="progress" :percent="downLoadPercent" activeColor="#3DA7FF" show-info
									stroke-width="10" />
								<view
									style="width: 100%; font-size: 28rpx; display: flex; justify-content: space-around">
									<text>{{ downLoadingText }}</text>
									<text>({{ downloadedSize }}/{{ packageFileSize }}M)</text>
								</view>
							</view>

							<button v-else class="content-button" style="border: none; color: #fff" plain
								@click="downloadPackage">
								{{ downLoadBtnText }}
							</button>
						</template>

						<button v-else-if="downloadSuccess && !installed" class="content-button"
							style="border: none; color: #fff" plain :loading="installing" :disabled="installing"
							@click="installPackage">
							{{ installing ? '正在安装……' : '下载完成，立即安装' }}
						</button>

						<button v-else-if="installed" class="content-button" style="border: none; color: #fff" plain
							@click="restart">安装完毕，点击重启</button>
					</template>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import request from '@/utils/request';
	import {
		ref,
		reactive,
		toRefs,
		onMounted,
		computed,
	} from 'vue';

	defineOptions({
		name: 'gyd-upgrade-app'
	});

	onMounted(() => {
		console.log('组件已挂载');
		checkVersion();
	});

	const state = reactive({
		// 安装
		installed: false,
		installing: false,

		// 下载
		downloadSuccess: false,
		downloading: false,

		downLoadPercent: 0,
		downloadedSize: 0,
		packageFileSize: 0,

		tempFilePath: '', // 要安装的本地包地址

		// 默认安装包信息
		title: 'APP更新',
		version: '1.0.0',
		contents: '接入uni统计<br>解决微信自定义组件运行失败的Bug',
		is_mandatory: false,
		url: '',
		platform: [],
		type: '',

		// 可自定义属性
		subTitle: '发现新版本',
		downLoadBtnTextiOS: '立即跳转更新',
		downLoadBtnText: '立即下载更新',
		downLoadingText: '安装包下载中，请稍后',
	});

	let downloadTask = null;

	const isApplicationStore = computed(() => {
		return !isWGT && isNativeApp && (isiOS || isHarmony);
	})

	const isWGT = computed(() => {
		return state.type === 'wgt';
	})

	const isNativeApp = computed(() => {
		return state.type === 'native_app';
	})

	const isiOS = computed(() => {
		return state.platform.indexOf('iOS') !== -1;
	})

	const isAndroid = computed(() => {
		return state.platform.indexOf('Android') !== -1;
	})

	const isHarmony = computed(() => {
		return state.platform.indexOf('Harmony') !== -1;
	})

	const needNotificationProgress = computed(() => {
		return state.platform.indexOf('iOS') === -1 && !state.is_mandatory && !isHarmony;
	})

	//检查版本
	function checkVersion() {
		uni.getSystemInfo({
			success: (data) => {
				console.log('系统信息', data);
				state.platform = data.platform;
				request.get('index/getAppVersion', {
					version: data.appVersion,
					appType: 'manage',
					platformType: data.platform
				}).then(res => {
					console.log('获取更新', res);
					if (res.code == 1) {
						if (res.data.isUpdate) {
							console.log('需要更新', res.data.isUpdate);
							state.version = res.data.new_version;
							state.contents = res.data.update_text;
							state.url = res.data.download_url;
						} else {
							console.log('不需要更新', res.data.isUpdate);
						}
					}
				})
			}
		})
	}

	//跳转应用商店
	function jumpToApplicationStore() {
		plus.runtime.openURL(state.url);
	}

	function downloadPackage() {
		state.downloading = true;
		//下载包
		downloadTask = uni.downloadFile({
			url: state.url,
			success: (res) => {
				console.log('下载包', res);
				if (res.statusCode == 200) {
					// fix: wgt 文件下载完成后后缀不是 wgt
					if (isWGT && res.tempFilePath.split('.').slice(-1)[0] !== 'wgt') {
						const failCallback = (e) => {
							console.log('[FILE RENAME FAIL]：', JSON.stringify(e));
						};
						// #ifndef APP-HARMONY
						plus.io.resolveLocalFileSystemURL(
							res.tempFilePath,
							(entry) => {
								entry.getParent((parent) => {
									const newName = `new_wgt_${Date.now()}.wgt`;
									entry.copyTo(
										parent,
										newName,
										(res) => {
											state.tempFilePath = res.fullPath;
											downLoadComplete();
										},
										failCallback
									);
								}, failCallback);
							},
							failCallback
						);
						// #endif
						// #ifdef APP-HARMONY
						failCallback({
							code: -1,
							message: 'Download content error, is not wgt.'
						})
						// #endif
					} else {
						state.tempFilePath = res.tempFilePath;
						downLoadComplete();
					}
				} else {
					console.log('下载错误-1：' + JSON.stringify(res));
					downloadFail();
				}
			},
			fail: (err) => {
				console.log('下载错误-2：' + JSON.stringify(err));
				downloadFail();
			}
		});
	}

	function downLoadComplete() {
		state.downloadSuccess = true;
		state.downloading = false;

		state.downLoadPercent = 0;
		state.downloadedSize = 0;
		state.packageFileSize = 0;

		downloadTask = null;

		if (needNotificationProgress) {
			uni.showModal({
				title: '安装升级包',
				content: '下载完成',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})

			installPackage();
			return;
		}

		// 强制更新，直接安装
		if (state.is_mandatory) {
			installPackage();
		}
	}

	function downloadFail() {
		const errMsg = '下载失败，请点击重试'

		state.downloadSuccess = false;
		state.downloading = false;

		state.downLoadPercent = 0;
		state.downloadedSize = 0;
		state.packageFileSize = 0;

		state.downLoadBtnText = errMsg

		downloadTask = null;

		if (needNotificationProgress) {
			uni.showModal({
				title: '升级包下载失败',
				content: '请重新检查更新',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		}
	}

	function installPackage() {
		// #ifdef APP-PLUS || APP-HARMONY
		// wgt资源包安装
		if (isWGT) {
			state.installing = true;
		}
		plus.runtime.install(
			state.tempFilePath, {
				force: false
			},
			async (res) => {
					state.installing = false;
					state.installed = true;

					// wgt包，安装后会提示 安装成功，是否重启
					if (isWGT) {
						// 强制更新安装完成重启
						if (state.is_mandatory) {
							// #ifdef APP-PLUS
							uni.showLoading({
								icon: 'none',
								title: '安装成功，正在重启……'
							});
							// #endif

							setTimeout(() => {
								// #ifdef APP-PLUS
								uni.hideLoading();
								// #endif
								restart();
							}, 1000);
						}
					} else {
						const localFilePathRecord = uni.getStorageSync(localFilePathKey);
						uni.setStorageSync(localFilePathKey, {
							...localFilePathRecord,
							installed: true
						});
					}
				},
				async (err) => {
					// 安装失败需要重新下载安装包
					state.installing = false;
					state.installed = false;

					uni.showModal({
						title: '更新失败，请重新下载',
						content: err.message,
						showCancel: false
					});
				}
		);

		// 非wgt包，安装跳出覆盖安装，此处直接返回上一页
		if (!isWGT && !state.is_mandatory) {
			uni.navigateBack();
		}
		// #endif
	}

	function restart() {
		state.installed = false;
		// #ifdef APP-HARMONY
		uni.showModal({
			title: '更新完毕',
			content: '请手动重启',
			showCancel: false,
			success(res) {
				plus.runtime.quit()
			}
		})
		// #endif

		// #ifdef APP-PLUS
		//更新完重启app
		plus.runtime.restart();
		// #endif
	}

	const popupRef = ref(null);

	function handleOpen() {
		popupRef.value.open();
	}

	function handleClose() {
		popupRef.value.close();
	}

	defineExpose({
		open: handleOpen,
		close: handleClose
	});

	const {
		installed,
		installing,
		downloadSuccess,
		downloading,
		downLoadPercent,
		downloadedSize,
		packageFileSize,
		tempFilePath,
		title,
		version,
		contents,
		is_mandatory,
		url,
		platform,
		type,
		subTitle,
		downLoadBtnTextiOS,
		downLoadBtnText,
		downLoadingText,
	} = toRefs(state);
</script>

<style lang="scss" scoped>
	//弹出面板
	.show-panel {
		.close-icon {
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			z-index: 1000;
		}

		.content {
			position: relative;
			top: 0;
			width: 600rpx;
			background-color: #fff;
			box-sizing: border-box;
			padding: 0 50rpx;
			font-family: Source Han Sans CN;

			.content-top {
				position: absolute;
				top: -195rpx;
				left: 0;
				width: 600rpx;
				height: 270rpx;

				.content-top-text {
					font-size: 45rpx;
					font-weight: bold;
					color: #f8f8fa;
					position: absolute;
					top: 120rpx;
					left: 50rpx;
					z-index: 1;
				}

				.content-top-img {
					width: 600rpx;
					height: 270rpx;
				}
			}

			.content-header {
				height: 80rpx;
			}

			.content-body {
				width: 100%;

				.title {
					font-size: 33rpx;
					font-weight: bold;
					color: #3da7ff;
					line-height: 38px;

					.content-body-version {
						padding-left: 20rpx;
						color: #fff;
						font-size: 20rpx;
						margin-left: 10rpx;
						padding: 4rpx 8rpx;
						border-radius: 20rpx;
						background: #50aefd;
					}
				}

				.body {
					.box-des-scroll {
						box-sizing: border-box;
						padding: 0 40rpx;
						height: 200rpx;
						text-align: left;

						.box-des {
							font-size: 26rpx;
							color: #000000;
							line-height: 50rpx;
						}
					}
				}
			}

			.footer {
				height: 150rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.content-button {
					text-align: center;
					flex: 1;
					font-size: 30rpx;
					font-weight: 400;
					color: #ffffff;
					border-radius: 40rpx;
					margin: 0 18rpx;
					height: 80rpx;
					line-height: 80rpx;
					background: linear-gradient(to right, #1785ff, #3da7ff);
				}

				.progress-box {
					width: 100%;

					.progress {
						width: 90%;
						height: 40rpx;
					}
				}

				.flex-column {
					display: flex;
					flex-direction: column;
					align-items: center;
				}
			}
		}
	}
</style>